<?php
	session_start();
	
	function currentPageURL() {
		 $pageURL = 'http';
		 if(isset($_SERVER["HTTPS"]))
		 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
		 $pageURL .= "://";
		 if ($_SERVER["SERVER_PORT"] != "80") {
		  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
		 } else {
		  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		 }
		 $pageURL= str_replace("search-ajax.php","search.php",$pageURL);
		 $pageURL= str_replace("&","&amp;",$pageURL);
		 echo $pageURL;
		 return $pageURL;
	}
	
function getIDNumber($tablename, $itemname){
	$message= "";
	require('config/mysql.config.inc');
	$mysqli = new mysqli($host, $username, $password, $db);	

	if($tablename == "CategoryTypes"){$idname = "categoryid"; $name = "cname";}
	if($tablename == "FinishTypes"){$idname = "finishid"; $name = "fname";}
	if($tablename == "ShapeTypes"){$idname = "shapeid"; $name = "sname";}
	if($tablename == "MaterialTypes") {$idname = "materialid"; $name = "mname";}
	if($tablename == "Sets") {$idname = "setid"; $name = "setname";}
	if($tablename == "Pieces") {$idname = "modelno"; $name = "pname";}
	if($tablename == "Types") {$idname = "typeid"; $name = "tname";}
	if($tablename == "Wishlists") {$idname = "wishlistid"; $name = "wname";}
	if($tablename == "Users") {$idname = "uid"; $name = "email";}

	if(isset($idname)){
		$result = $mysqli->query("SELECT " . $idname . " FROM ". $tablename . " WHERE " . $name . " = '" . $itemname . "'");
		if($result->num_rows != 0){
			$ans = $result->fetch_assoc();
			$id = $ans[$idname];
			return $id;
		}
		else{
			$message .="No results!";

		}	
	}
	else{
		$message .= "This function doesn't work with this table\n";
	}

}

	$_SESSION['hasSearched']= true;
	$squery="";
	$_SESSION['search_query']= $squery;
	$_SESSION['categorymod']= "0";
	$_SESSION['typemod']= "0";
	$_SESSION['finishmod']= "0";
	$_SESSION['materialmod']= "0";
	$_SESSION['shapemod']= "0";
	if (isset($_POST['search_query'])) {
		$squery=$_POST['search_query'];
	}
	
	$categoryid= null;
	$typeid= null;
	$finishid= null;
	$materialid= null;
	$shapeid= null;
	$conditions= null;
		$page = 'search';
		include ('includes/header.php');
		include('includes/menubar.php');
?>

<div class="body_content">
	<!--Give the user options to modify their search query-->
	<p class="message"><strong>Search the Catalog</strong></p>
	<?php
	//Connect to the database
	require('config/mysql.config.inc');
	$mysqli = new mysqli($host, $username, $password, $db);	
		
	if(isset($_GET['queryModified'])){
		if($_GET['queryModified'] == 0){
			$squery= $_GET['search_query'];
			$_SESSION['search_query']= $squery;
			if ($squery=="") {
				$squery=" ";
			}
			$conditions= "modelno REGEXP '".$squery."' OR pname REGEXP '".$squery."' OR description REGEXP '".$squery."' OR cname REGEXP '".$squery."' OR fname REGEXP '".$squery."' OR mname REGEXP '".$squery."' OR sname REGEXP '".$squery."'";
			//$conditions= "modelno REGEXP '".$squery."' OR pname REGEXP '".$squery."' OR description REGEXP '".$squery."' OR cname REGEXP '".$squery."' OR fname REGEXP '".$squery."' OR mname REGEXP '".$squery."' OR sname REGEXP '".$squery."'";

		}
		else {//if($_GET['queryModified'] == 1){
			$squery= $_GET['search_query2'];
			$_SESSION['search_query']= $squery;
			$_SESSION['queryModified']= 1;
			$categoryspecs= null;
			$typespecs= null;
			$finishspecs= null;
			$materialspecs= null;
			$shapespecs= null;
			if($_GET['categorymod'] != "0"){
				$categoryspecs= " AND categoryid = '".$_GET['categorymod']."'";
				$_SESSION['categorymod']= $_GET['categorymod'];				
			}else{$_SESSION['categorymod']= "0";}			
			if($_GET['typemod'] != "0"){
				$typespecs= " AND typeid = '".$_GET['typemod']."'";	
				$_SESSION['typemod']= $_GET['typemod'];							
			}else{$_SESSION['typemod']= "0";}					
			if($_GET['finishmod'] != "0"){
				$finishspecs= " AND finishid = '".$_GET['finishmod']."'";
				$_SESSION['finishmod']= $_GET['finishmod'];								
			}else{$_SESSION['finishmod']= "0";}					
			if($_GET['materialmod'] != "0"){
				$materialspecs= " AND materialid = '".$_GET['materialmod']."'";	
				$_SESSION['materialmod']= $_GET['materialmod'];							
			}else{$_SESSION['materialmod']= "0";}				
			if($_GET['shapemod'] != "0"){
				$shapespecs= " AND shapeid = '".$_GET['shapemod']."'";
				$_SESSION['shapemod']= $_GET['shapemod'];								
			}else{$_SESSION['shapemod']= "0";}			
						
			//$conditions= "modelno REGEXP '".$squery."' OR pname REGEXP '".$squery."'".$categoryspecs."".$typespecs."".$finishspecs."".$materialspecs."".$shapespecs."";
			if ($squery=="") {
				$squery=" ";
			}
			$conditions= "(modelno REGEXP '".$squery."' OR pname REGEXP '".$squery."' OR description REGEXP '".$squery."' OR cname REGEXP '".$squery."' OR fname REGEXP '".$squery."' OR mname REGEXP '".$squery."' OR sname REGEXP '".$squery."') ".$categoryspecs."".$typespecs."".$finishspecs."".$materialspecs."".$shapespecs."";

		}
	}
	else{
		$_SESSION['categorymod']= "0";
		$_SESSION['typemod']= "0";
		$_SESSION['finishmod']= "0";
		$_SESSION['materialmod']= "0";
		$_SESSION['shapemod']= "0";
	}
		
		
	print("<form action=\"search.php\" method=\"get\">
		<p class=\"center\">Search Query: <input type=\"text\" value=\"".$_SESSION['search_query']."\" id=\"search_query2\" name=\"search_query2\"/></p>
		<fieldset class=\"center\">
			<select id=\"categorymod\" name=\"categorymod\">");			
		
	
	//Display the results and advanced search options
	$categoriesQuery= "SELECT cname, categoryid FROM CategoryTypes ORDER BY cname;";
	$typesQuery= "SELECT tname, typeid FROM Types ORDER BY tname;";
	$finishesQuery= "SELECT fname, finishid FROM FinishTypes ORDER BY fname;";
	$materialsQuery= "SELECT mname, materialid FROM MaterialTypes ORDER BY mname;";
	$shapesQuery= "SELECT sname, shapeid FROM ShapeTypes ORDER BY sname;";
	$result= $mysqli->query($categoriesQuery);
	print("<option id=\"category0\" value=\"0\">Select a category</option>");
	$i=1;
	while($categories= $result->fetch_assoc()){
		$category= $categories['cname'];
		$categoryid= $categories['categoryid'];
		//Maintain selected values
		if(isset($_GET['categorymod'])){
			$categoryselected= $_GET['categorymod'];
		}
		else{
			$categoryselected= null;
		}
		if($categoryselected == $categoryid){
			print("<option id=\"category".$i."\" value=\"".$categoryid."\" selected>$category</option>");
			$i++;
		}
		else{
			print("<option id=\"category".$i."\" value=\"".$categoryid."\">$category</option>");
			$i++;
		}		
	}
	print("</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
	
	print("<select id=\"typemod\" name=\"typemod\">");
	$result= $mysqli->query($typesQuery);
	print("<option id=\"type0\" value=\"0\">Select a type of furniture</option>");
	$i=1;
	while($types= $result->fetch_assoc()){
		$type= $types['tname'];
		$typeid= $types['typeid'];
		if(isset($_GET['typemod'])){
			$typeselected= $_GET['typemod'];
		}
		else{
			$typeselected= null;
		}
		if($typeselected == $typeid){
			print("<option id=\"type".$i."\" value=\"".$typeid."\" selected>$type</option>");
			$i++;
		}
		else{
			print("<option id=\"type".$i."\" value=\"".$typeid."\">$type</option>");
			$i++;
		}
	}
	print("</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
	
	print("<select id=\"finishmod\" name=\"finishmod\">");
	$result= $mysqli->query($finishesQuery);
	print("<option id=\"finish0\" value=\"0\">Select a finish</option>");
	$i=1;
	while($finishes= $result->fetch_assoc()){
		$finish= $finishes['fname'];
		$finishid= $finishes['finishid'];
		if(isset($_GET['finishmod'])){
			$finishselected= $_GET['finishmod'];
		}
		else{
			$finishselected= null;
		}
		if($finishselected == $finishid){
			print("<option id=\"finish".$i."\" value=\"".$finishid."\" selected>$finish</option>");
			$i++;
		}
		else{
			print("<option id=\"finish".$i."\" value=\"".$finishid."\">$finish</option>");
			$i++;
		}		
	}
	print("</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
	
	print("<select id=\"materialmod\" name=\"materialmod\">");
	$result= $mysqli->query($materialsQuery);
	print("<option id=\"material0\" value=\"0\">Select a material</option>");
	$i=1;
	while($materials= $result->fetch_assoc()){
		$material= $materials['mname'];
		$materialid= $materials['materialid'];
		if(isset($_GET['materialmod'])){
			$materialselected= $_GET['materialmod'];
		}
		else{
			$materialselected= null;
		}
		if($materialselected == $materialid){
			print("<option id=\"material".$i."\" value=\"".$materialid."\" selected>$material</option>");
			$i++;	
		}
		else{
			print("<option id=\"material".$i."\" value=\"".$materialid."\">$material</option>");
			$i++;
		}
	}
	print("</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");	
	
	print("<select id=\"shapemod\" name=\"shapemod\">");
	$result= $mysqli->query($shapesQuery);
	print("<option id=\"shape0\" value=\"0\">Select a shape</option>");
	$i=1;
	while($shapes= $result->fetch_assoc()){
		$shape= $shapes['sname'];
		$shapeid= $shapes['shapeid'];
		if(isset($_GET['materialmod'])){
			$shapeselected= $_GET['shapemod'];
		}
		else{
			$shapeselected= null;
		}
		if($shapeselected == $shapeid){
			print("<option id=\"shape".$i."\" value=\"".$shapeid."\" selected>$shape</option>");
			$i++;
		}
		else{
			print("<option id=\"shape".$i."\" value=\"".$shapeid."\">$shape</option>");
			$i++;
		}
	}
	echo'</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	<input type="hidden" name="queryModified" value="1" />
	<input type="submit" name="searchmodify" value="Go" />
	</fieldset>	
	</form>';
	print("<div id=\"output\">");	
	
		
		//Search the database

			$searchQuery= "SELECT * FROM Pieces NATURAL JOIN CategoryTypes NATURAL JOIN FinishTypes NATURAL JOIN MaterialTypes NATURAL JOIN ShapeTypes WHERE ".$conditions;

		$searchResult= $mysqli->query($searchQuery);
		
		if ($searchResult==null || $searchResult->num_rows==0) {
			print("<div>No results. Please try broadening your search criteria.</div>");	
		} else {
			while($sResults= $searchResult->fetch_assoc()){
				print("\n\t<div class=\"searched_furniture\">");
				print("<div class=\"furniture_options\">");

				if(isset($_SESSION['user'])){				
				//ADDING AND EDITING AS LOGGED USER		
				print("<form action=\"edititem.php\" method=\"get\">");
				$uid = getIDNumber("Users", $_SESSION['user']);
				print("Wishlists:");
				$resultwishlist = $mysqli->query("SELECT * FROM Wishlists WHERE uid = '" . $uid . "' ORDER BY wname;");
				print("<select name=\"addwishlist\">");
				if($resultwishlist->num_rows == 0){
					print "Error: Please Create a Wishlist before you can add this item!<br/>";
				}
				else{
					$i = 0;
					while($wishlist = $resultwishlist->fetch_assoc()){
						$i++;
						print "<option>" . $wishlist["wname"] . "</option>";
					}
				}
				print("</select>");
				print("<input type=\"hidden\" name=\"modelno\" value=\"" . $sResults['modelno'] . "\"/>");							
				print("<input type=\"submit\" value=\"Add and Edit in Wishlist\" />");
				print("</form>");
			}
			else{
				print("<a href =\"useracct.php\"> Add Item To Wishlist </a><br/><br/>");			
			}
			print("</div>");			
			
			print("<div class=\"furniture_right_search\"><em>". $sResults['description']."</em><br/><br/>");
			$temp= $mysqli->query("SELECT tname FROM Types WHERE typeid='".$sResults['typeid']."'");
			$temp=$temp->fetch_row();
			print("Item: <em>".$temp[0]."</em><br/>");
			
			$temp=$mysqli->query("SELECT fname FROM FinishTypes WHERE finishid='" . $sResults['finishid'] ."'");
			$temp=$temp->fetch_row();
			print("Finish: <em>" . $temp[0]."</em>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;");
			
			$temp=$mysqli->query("SELECT mname FROM MaterialTypes WHERE materialid='" . $sResults['materialid'] ."'");
			$temp=$temp->fetch_row();
			print("Material: <em>" . $temp[0]."</em><br/>");
			
			$temp=$mysqli->query("SELECT sname FROM ShapeTypes WHERE shapeid='" . $sResults['shapeid'] ."'");
			$temp=$temp->fetch_row();
			print("Shape: <em>" . $temp[0]."</em>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;");
			
			print("Dimensions: " . $sResults['length'] . "x" . $sResults['width'] . "x" . $sResults['height']."<br/>");
			print("Model Number: " . $sResults['modelno']."<br/><a href=\"");
			echo currentPageURL();
			print("#top\">Back to Top</a>");
			
			print("</div>");
			print("<div class=\"furniture_left\">");
			//Print out each photo along with associated pieces, description, specs, and model number
			print("<br/>\t\t" . $sResults['pname']);
	
			$url = explode("/", $sResults['photourl']);
			$temp= $mysqli->query("SELECT cname FROM CategoryTypes WHERE categoryid='".$sResults['categoryid']."'");
			$temp=$temp->fetch_row();
			$temp=$temp[0];
			if($temp == "Kitchen"){
				$tempPage="kitchen";
			}
			elseif($temp == "Dining Room"){
				$tempPage="diningroom";
			}
			else{
				$tempPage="misc";
			}
			print("<br/>\t\t<a href=\"furniture.php?page=".$tempPage."&amp;modelno=" . $sResults['modelno'] . "\"><img alt=\"furntiurePhoto\" src=\"furniturethumbs/".$url[1]."\"/> </a>");
			print("<br/>\n\t\t<span class=\"smaller-font\"> Click picture for more details...</span>\n");	
			print("\n\t</div>\n");
			print("\n\t</div>\n");
			}				
		}


			print("</div>");			
		
			//Close the connection to the database
			$mysqli->close();
		?>	
	</div>
	<?php
	include ('includes/footer.php');
	?>
</body>
</html>